<?php

/**
 * Image Resource Model
 */
class AW_Imagetest_Model_Mysql4_Image extends Mage_Core_Model_Mysql4_Abstract
{
    /**
     * Class constructor
     */
    protected function _construct()
    {
        $this->_init('imagetest/image', 'image_id');
    }

    /**
     * Processing object before save data
     * @return Mage_Core_Model_Abstract
     */
    protected function _beforeSave(Mage_Core_Model_Abstract $object)
    {
        parent::_beforeSave($object);
        $date = new Zend_Date();
        $object->setUpdatedAt($date->toString('YYYY-MM-dd HH:mm'));
        return $this;
    }

    /**
     * Processing object after save data
     * @return AW_Imagetest_Model_Mysql4_Image
     */
    protected function _afterSave(Mage_Core_Model_Abstract $object)
    {
        parent::_afterSave($object);
        $this->_saveStores($object);
        $this->_saveComment($object);
        return $this;
    }

    /**
     * Load comment to model
     * @param Mage_Core_Model_Abstract $object
     * @return AW_Imagetest_Model_Mysql4_Image
     */
    public function loadComment(Mage_Core_Model_Abstract $object)
    {
        $this->_loadComment($object);
        return $this;
    }

    /**
     * Load stores to model
     * @param Mage_Core_Model_Abstract $object
     * @return AW_Imagetest_Model_Mysql4_Image
     */
    public function loadStores(Mage_Core_Model_Abstract $object)
    {
        $this->_loadStores($object);
        return $this;
    }

    /**
     * Load stores to model
     * @param Mage_Core_Model_Abstract $object
     * @return AW_Imagetest_Model_Mysql4_Image
     */
    protected function _loadStores(Mage_Core_Model_Abstract $object)
    {
        $image_id = $object->getImageId();
        $imageStore = $this->getTable('imagetest/store');
        $select = new Zend_Db_Select($this->_getReadAdapter());
        $select->from($imageStore, array('store_id'))
                ->where('image_id = ?', $image_id)
                ;
        $stores = array();
        foreach ($select->query() as $store){
            $stores[] = $store['store_id'];
        }
        $object->setStores($stores);
        return $this;
    }

    /**
     * Load comment to model
     * @param Mage_Core_Model_Abstract $object
     * @return AW_Imagetest_Model_Mysql4_Image
     */
    protected function _loadComment(Mage_Core_Model_Abstract $object)
    {
        $image_id = $object->getImageId();
        $imageComment = $this->getTable('imagetest/comment');
        $select = new Zend_Db_Select($this->_getReadAdapter());
        $select->from($imageComment, array('comment'))
                ->where('image_id = ?', $image_id)
                ;       
        if ($comment = $this->_getReadAdapter()->fetchOne($select)){
            $object->setComment($comment);
        }        
        return $this;
    }

    /**
     * Save comment to db
     * @param Mage_Core_Model_Abstract $object
     * @return AW_Imagetest_Model_Mysql4_Image
     */
    protected function _saveComment(Mage_Core_Model_Abstract $object)
    {
        $image_id = $object->getImageId();
        $imageComment = $this->getTable('imagetest/comment');
        if (!$object->getComment()){
            $this->_getWriteAdapter()->delete(
                $imageComment,
                $this->_getWriteAdapter()->quoteInto('image_id=?', $image_id)
            );            
            return $this;
        }
        $select = new Zend_Db_Select($this->_getReadAdapter());
        $select->from($imageComment, array('comment'))
                ->where('image_id = ?', $image_id)
                ;       
        $comment = $this->_getReadAdapter()->fetchOne($select);
        if ($comment == $object->getComment()){
            return $this;
        }
        if ($comment){
            $this->_getWriteAdapter()->update($imageComment,
                array('comment' => $object->getComment()),
                'image_id='.(int)$image_id
            );
        } else {
            $row = array(
                'image_id' => $image_id,
                'comment' => $object->getComment()
            );

            $fields = array();
            $values = array();
            foreach ($row as $k => $v) {
                $fields[] = $this->_getWriteAdapter()->quoteIdentifier('?', $k);
                $values[] = $this->_getWriteAdapter()->quoteInto('?', $v);
            }
            $sql = sprintf('INSERT IGNORE INTO %s (%s) VALUES(%s)',
                $this->_getWriteAdapter()->quoteIdentifier($imageComment),
                join(',', array_keys($row)),
                join(',', $values));
            $this->_getWriteAdapter()->query($sql);            
        }
        return $this;
    }

    /**
     * Save stores to db
     * @param Mage_Core_Model_Abstract $object
     * @return AW_Imagetest_Model_Mysql4_Image
     */
    protected function _saveStores(Mage_Core_Model_Abstract $object)
    {
        $image_id = $object->getImageId();
        $imageStore = $this->getTable('imagetest/store');

        $this->_getWriteAdapter()->delete(
            $imageStore,
            $this->_getWriteAdapter()->quoteInto('image_id=?', $image_id)
        );
        
        $stores = $object->getStores();
        if (count($stores)){
            foreach ($stores as $store_id){
                $row = array(
                    'image_id' => $image_id,
                    'store_id' => $store_id
                );

                $fields = array();
                $values = array();
                foreach ($row as $k => $v) {
                    $fields[] = $this->_getWriteAdapter()->quoteIdentifier('?', $k);
                    $values[] = $this->_getWriteAdapter()->quoteInto('?', $v);
                }
                $sql = sprintf('INSERT IGNORE INTO %s (%s) VALUES(%s)',
                    $this->_getWriteAdapter()->quoteIdentifier($imageStore),
                    join(',', array_keys($row)),
                    join(',', $values));
                $this->_getWriteAdapter()->query($sql);
            }
        }

        return $this;
    }
    
    /**
     * Processing object after load data
     * @return Mage_Core_Model_Abstract
     */
    protected function _afterLoad(Mage_Core_Model_Abstract $object)
    {
        parent::_afterLoad($object);
        $this->_loadStores($object);
        $this->_loadComment($object);           
        return $this;
    }
}

